function trial = FindThePeak(trialdata, times, windowTimes, positive)

if positive
    windowMin = min(find(times > windowTimes(1)));
    windowMax = max(find(times < windowTimes(2)));
    [pks,locs] = findpeaks(trialdata(windowMin:windowMax),'npeaks',1);
    if isempty(locs)
        [pks, locs] = max(trialdata(windowMin:windowMax));
    end
    trial.time = times(windowMin + locs);
    trial.value = trialdata(windowMin + locs);
else
    windowMin = min(find(times > windowTimes(1)));
    windowMax = max(find(times < windowTimes(2)));
    [pks,locs] = findpeaks(-trialdata(windowMin:windowMax),'npeaks',1);
    if isempty(locs)
        [pks, locs] = min(trialdata(windowMin:windowMax));
    end
    trial.time = times(windowMin + locs);
    trial.value = trialdata(windowMin + locs);
end


end